﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;

namespace HaiTaoTools
{
    public class Whios
    {
        /// <summary>
        /// 域名注册信息
        /// </summary>
        /// <param name="domain">输入域名，不包含www</param>
        /// <returns></returns>
        public static string GetWhios(string domain)
        {
            string whoisServer = "whois.hichina.com";

            if (domain == null)
                throw new ArgumentNullException();
            int ccStart = domain.LastIndexOf(".");
            if (ccStart < 0 || ccStart == domain.Length)
                throw new ArgumentException();


            string ret = "";
            Socket s = null;
            try
            {
                string cc = domain.Substring(ccStart + 1);
                s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.SendTimeout = 900;
                s.Connect(new IPEndPoint(Dns.Resolve(whoisServer).AddressList[0], 43));
                s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
                byte[] buffer = new byte[1024];
                int recv = s.Receive(buffer);
                while (recv > 0)
                {
                    ret += Encoding.Default.GetString(buffer, 0, recv);
                    recv = s.Receive(buffer);
                }
                s.Shutdown(SocketShutdown.Both);


            }
            catch (SocketException ex)
            {
                return ex.Message;
            }
            finally
            {
                if (s != null)
                    s.Close();
            }

            return ret;
        }

    }
}
